package com.harvest.scientific.ladder.page

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.harvest.scientific.ladder.R
import com.harvest.scientific.ladder.base.BaActivity
import com.harvest.scientific.ladder.databinding.ActInfo1Binding
import com.harvest.scientific.ladder.ext.asLifecycleOwner
import com.harvest.scientific.ladder.ext.visible
import com.harvest.scientific.ladder.page.adapter.EmailAdapter
import com.harvest.scientific.ladder.res.RegardMostBeehiveRes
import com.harvest.scientific.ladder.res.RememberBlankAntRes
import com.harvest.scientific.ladder.util.FlowBus
import com.harvest.scientific.ladder.util.FlowBusConstant
import com.harvest.scientific.ladder.util.StbarUtil
import com.harvest.scientific.ladder.util.ToastUtil
import com.harvest.scientific.ladder.wheel.address.AddressPicker
import com.harvest.scientific.ladder.wheel.address.OnAddressSelectedListener
import com.harvest.scientific.ladder.wheel.wheelpicker.BirthdayPicker
import com.harvest.scientific.ladder.wheel.wheelpicker.SexPicker

class Info1Activity: BaActivity(),View.OnClickListener {

    private lateinit var binding: ActInfo1Binding

    private lateinit var areaPicker: AddressPicker
    private var provinceSelect: RegardMostBeehiveRes? = null
    private var citySelect: RegardMostBeehiveRes? = null
    private var areaSelect: RegardMostBeehiveRes? = null

    private lateinit var birthdayPicker: BirthdayPicker

    private lateinit var sexPicker: SexPicker
    private var sexSelect: RememberBlankAntRes?= null

    private var emailAdapter = EmailAdapter()
    private var emailList: MutableList<String> = arrayListOf("gmail.com","hotmail.com","yahoo.com","outlook.com")
    val tempList: MutableList<String> = mutableListOf()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        StbarUtil.setStatusBar(this,false, Color.TRANSPARENT,true)
        binding = ActInfo1Binding.inflate(layoutInflater)
        setContentView(binding.root)
        initEvent()
        initTextChangedListener()
        initObserver()
        initAdapter();
        initData()
    }

    private fun initAdapter() {
        binding.rvEmail.layoutManager = LinearLayoutManager(this@Info1Activity)
        binding.rvEmail.adapter = emailAdapter
        emailAdapter.addAll(emailList)
        emailAdapter.setOnItemClickListener { adapter, view, position ->
            runCatching {
                var content = binding.etEmail.text.toString().trim()
                val index = content.indexOfLast { it == '@' }
                if (index > -1) {
                    content = "${content.subSequence(0,index)}@${adapter.getItem(position)}"
                } else {
                    content = "${adapter.getItem(position)}"
                }
                binding.etEmail.setText(content)
                binding.etEmail.setSelection(content.length)
                binding.rvEmail.visible(false)
            }
        }
    }

    private fun initObserver () {
//        FlowBus.with<Unit>(FlowBusConstant.CLOSE_INFO).register(this) {
//            finish()
//        }

        appModel.showLoading.observe(asLifecycleOwner) {
            if (it) showLoading() else dismissLoading()
        }
        appModel.searchInfo1.observe(asLifecycleOwner) { result ->
            result?.let {
                if (!it.festivalPaper.isNullOrEmpty()) {
                    binding.etName1.setText(it.festivalPaper)
                }
                if (!it.suddenGasTwin.isNullOrEmpty()) {
                    binding.etName2.setText(it.suddenGasTwin)
                }
                if (!it.unsuccessfulFavouriteEmbassy.isNullOrEmpty()) {
                    binding.iBirthday.tvContent.text = it.unsuccessfulFavouriteEmbassy
                }
                if (!it.southRecordSureSleeve.isNullOrEmpty()) {
                    sexSelect = RememberBlankAntRes(it.actualStreamColdVinegar,it.southRecordSureSleeve)
                    binding.iSex.tvContent.text = it.southRecordSureSleeve
                }
                if (!it.furnishedSink.isNullOrEmpty()) {
                    binding.etEmail.setText(it.furnishedSink)
                    binding.rvEmail.visible(false)
                }
                if (!it.indeedSoccerUsefulGuest.isNullOrEmpty() && !it.greyShineContributionCar.isNullOrEmpty() && !it.solidThereLake.isNullOrEmpty()
                    && !it.roundExerciseTroublesomeStranger.isNullOrEmpty() && !it.solidThereLake.isNullOrEmpty() && !it.allInternetSailingAgriculturalTiger.isNullOrEmpty()) {
                    provinceSelect = RegardMostBeehiveRes(
                        unhealthyCampAmericanLightning = it.indeedSoccerUsefulGuest,
                        fairCollegeElectricComputerRoundaboutDeparture = it.greyShineContributionCar
                    )
                    citySelect = RegardMostBeehiveRes(
                        unhealthyCampAmericanLightning = it.solidThereLake,
                        fairCollegeElectricComputerRoundaboutDeparture = it.roundExerciseTroublesomeStranger
                    )
                    areaSelect = RegardMostBeehiveRes(
                        unhealthyCampAmericanLightning = it.thinFriendCoolTastelessQuilt,
                        fairCollegeElectricComputerRoundaboutDeparture = it.allInternetSailingAgriculturalTiger
                    )
                    binding.iArea.tvContent.text = String.format(
                        "%s %s %s",
                        provinceSelect?.unhealthyCampAmericanLightning,
                        citySelect?.unhealthyCampAmericanLightning,
                        areaSelect?.unhealthyCampAmericanLightning,
                    )
                }
                if (!it.rapidNobleBestBacon.isNullOrEmpty()) {
                    binding.etCompleteAddress.setText(it.rapidNobleBestBacon)
                }
                if (!it.considerateHungerTomato.isNullOrEmpty()) {
                    binding.etCode.setText(it.considerateHungerTomato)
                }
                checkNextStatus()
            } ?: run {
                checkNextStatus()
            }
        }
        appModel.provinceList.observe(asLifecycleOwner) {
            areaPicker.setFirstData(it)
        }
        appModel.cityList.observe(asLifecycleOwner) {
            areaPicker.setSecondData(it)
        }
        appModel.areaList.observe(asLifecycleOwner) {
            areaPicker.setThirdData(it)
        }
        appModel.sexSuc.observe(asLifecycleOwner) {
            sexPicker.setJson(it)
        }
        appModel.saveInfo1Suc.observe(asLifecycleOwner) {
            dismissLoading()
            if (it) {
                startActivity(Intent(this@Info1Activity, Info2Activity::class.java))
            }
        }
    }

    private fun initData() {
        areaPicker = AddressPicker(this)
        birthdayPicker = BirthdayPicker(this)
        sexPicker = SexPicker(this)

        appModel.fleeSocialistExpedition(1)
        appModel.regardMostBeehive()
        appModel.rememberBlankAnt("sex")
    }

    private fun initEvent() {
        binding.llBack.setOnClickListener(this)
        binding.tvNext.setOnClickListener(this)
        binding.iBirthday.root.setOnClickListener(this)
        binding.iSex.root.setOnClickListener(this)
        binding.iArea.root.setOnClickListener(this)
        binding.tvProtocol.setOnClickListener(this)
    }

    private fun initTextChangedListener() {
        binding.etName1.addTextChangedListener(object : TextWatcher{
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                checkNextStatus()
            }
        })
        binding.etName2.addTextChangedListener(object : TextWatcher{
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                checkNextStatus()
            }
        })
        binding.etEmail.addTextChangedListener(object : TextWatcher{
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                if (!s.isNullOrEmpty()) {
                    if(s.last() == '@') {
                        emailAdapter.items = emailList
                        emailAdapter.notifyDataSetChanged()
                        binding.rvEmail.visible(true)
                    } else {
                        if (s.contains("@")) {
                            val index = s.indexOfLast { it == '@' }
                            val value = s.subSequence(index+1, s.length)
                            tempList.clear()
                            emailList.forEachIndexed { index, s ->
                                if (s.contains(value)) {
                                    tempList.add(s)
                                }
                            }
                            if (tempList.isNotEmpty()) {
                                emailAdapter.items = tempList
                                emailAdapter.notifyDataSetChanged()
                                binding.rvEmail.visible(true)
                            } else {
                                binding.rvEmail.visible(false)
                            }
                        } else {
                            binding.rvEmail.visible(false)
                        }
                    }
                } else {
                    binding.rvEmail.visible(false)
                }
                checkNextStatus()
            }
        })
        binding.etEmail.setOnFocusChangeListener { v, hasFocus ->
            if (!hasFocus) {
                binding.rvEmail.visible(false)
            }
        }
        binding.etCompleteAddress.addTextChangedListener(object : TextWatcher{
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                checkNextStatus()
            }
        })
        binding.etCode.addTextChangedListener(object : TextWatcher{
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                checkNextStatus()
            }
        })
    }

    override fun onClick(v: View) {
        binding.rvEmail.visible(false)
        when(v){
            binding.llBack -> {
                onBackPressed()
            }
            binding.tvNext -> {
                if (binding.etName1.text.toString().trim().isNullOrEmpty()) {
                    ToastUtil.showToast(getString(R.string.toast_info))
                    return
                }
                if (binding.etName2.text.toString().trim().isNullOrEmpty()) {
                    ToastUtil.showToast(getString(R.string.toast_info))
                    return
                }
                if (binding.iBirthday.tvContent.text.toString().trim().isNullOrEmpty()) {
                    ToastUtil.showToast(getString(R.string.toast_info))
                    return
                }
                if (binding.iBirthday.tvContent.text.toString().trim().isNullOrEmpty()) {
                    ToastUtil.showToast(getString(R.string.toast_info))
                    return
                }
                if (sexSelect?.antarcticEntry.isNullOrEmpty()) {
                    ToastUtil.showToast(getString(R.string.toast_info))
                    return
                }
                if (binding.etEmail.text.toString().trim().isNullOrEmpty()) {
                    ToastUtil.showToast(getString(R.string.toast_info))
                    return
                }
                if (provinceSelect?.fairCollegeElectricComputerRoundaboutDeparture.isNullOrEmpty()) {
                    ToastUtil.showToast(getString(R.string.toast_info))
                    return
                }
                if (binding.etCompleteAddress.text.toString().trim().isNullOrEmpty()) {
                    ToastUtil.showToast(getString(R.string.toast_info))
                    return
                }
                if (binding.etCode.text.toString().trim().isNullOrEmpty()) {
                    ToastUtil.showToast(getString(R.string.toast_info))
                    return
                }
                showLoading()
                appModel.realiseArabPrescription1(
                    mexicanRegardsMistakenRoofInterestingGallery = 1,
                    festivalPaper = binding.etName1.text.toString(),
                    suddenGasTwin = binding.etName2.text.toString(),
                    unsuccessfulFavouriteEmbassy = binding.iBirthday.tvContent.text.toString(),
                    southRecordSureSleeve = sexSelect?.antarcticEntry ?: "Mâle",
                    actualStreamColdVinegar = sexSelect?.furnishedLetterConnection ?: "0",
                    furnishedSink = binding.etEmail.text.toString(),
                    indeedSoccerUsefulGuest = provinceSelect?.fairCollegeElectricComputerRoundaboutDeparture ?: "",
                    greyShineContributionCar = provinceSelect?.unhealthyCampAmericanLightning ?: "0",
                    solidThereLake = citySelect?.fairCollegeElectricComputerRoundaboutDeparture ?:"",
                    roundExerciseTroublesomeStranger = citySelect?.unhealthyCampAmericanLightning ?: "0",
                    thinFriendCoolTastelessQuilt = areaSelect?.fairCollegeElectricComputerRoundaboutDeparture ?: "",
                    allInternetSailingAgriculturalTiger = areaSelect?.unhealthyCampAmericanLightning ?: "0",
                    rapidNobleBestBacon = binding.etCompleteAddress.text.toString(),//fullAddress 地址
                    considerateHungerTomato = binding.etCode.text.toString(),// codePin 邮政编码
                )
            }
            binding.iBirthday.root -> {
                if (binding.iBirthday.tvContent.text.isNullOrEmpty()) {
                    birthdayPicker.setDefaultValue(2000, 1, 1)
                } else {
                    runCatching {
                        val dayMonthYear: List<kotlin.String> = binding.iBirthday.tvContent.text.split("-")
                        birthdayPicker.setDefaultValue(dayMonthYear[2].toInt(), dayMonthYear[1].toInt(), dayMonthYear[0].toInt())
                    }
                }
                birthdayPicker.setOnDatePickedListener { year, month, day ->
                    binding.iBirthday.tvContent.text = String.format(
                        "%s-%s-%s",
                        day,
                        month,
                        year
                    )
                    checkNextStatus()
                }
                birthdayPicker.wheelLayout.setResetWhenLinkage(false)
                birthdayPicker.show()
            }
            binding.iSex.root -> {
                sexPicker.setDefaultValue(sexSelect)
                sexPicker.setBodyWidth(140)
                sexPicker.setIncludeSecrecy(false)
                sexPicker.setOnOptionPickedListener { position, item ->
                    sexSelect = item as RememberBlankAntRes?
                    binding.iSex.tvContent.text = sexPicker.wheelView.formatItem(position)
                    checkNextStatus()
                }
                sexPicker.wheelLayout
                    .setOnOptionSelectedListener { position, item ->
                        sexPicker.titleView.text = sexPicker.wheelView.formatItem(position)
                    }
                sexPicker.show()
            }
            binding.iArea.root -> {
                areaPicker.setDefaultValue(provinceSelect, citySelect, areaSelect)
                areaPicker.wheelLayout.setOnAddressSelectedListener(object : OnAddressSelectedListener{
                    override fun onFirstCallBack(pos: Int) {
                        if (!appModel.provinceList.value.isNullOrEmpty()) {
                            appModel.regardMostBeehive(
                                appModel.provinceList.value?.get(pos)?.unhealthyCampAmericanLightning ?: "",
                                "2"
                            )
                        }
                    }
                    override fun onSecondCallBack(pos: Int) {
                        if (!appModel.cityList.value.isNullOrEmpty()) {
                            appModel.regardMostBeehive(
                                appModel.cityList.value?.get(pos)?.femaleRecorderDrum ?: "",
                                "3"
                            )
                        }
                    }
                })
                areaPicker.setOnLinkageSelectedListener { first, second, third ->
                        binding.iArea.tvContent.text = String.format(
                            "%s %s %s",
                            areaPicker.firstWheelView.formatItem(first),
                            areaPicker.secondWheelView.formatItem(second),
                            areaPicker.thirdWheelView.formatItem(third)
                        )
                        provinceSelect = first as RegardMostBeehiveRes?
                        citySelect = second as RegardMostBeehiveRes?
                        areaSelect = third as RegardMostBeehiveRes?
                        checkNextStatus()
                    }
                areaPicker.show()
            }
            binding.tvProtocol -> {
                WebViewActivity.jumProtocol(this@Info1Activity)
            }
        }
    }

    private fun checkNextStatus(){
        if (getNextStatus()) {
            binding.tvNext.setBackgroundResource(R.drawable.bg_comon_sure_26)
        } else {
            binding.tvNext.setBackgroundResource(R.drawable.bg_comon_disable_sure_26)
        }
    }

    private fun getNextStatus(): Boolean {
        if (binding.etName1.text.toString().trim().isEmpty()) {
            return false
        }
        if (binding.etName2.text.toString().trim().isEmpty()) {
            return false
        }
        if (binding.iBirthday.tvContent.text.trim().isEmpty()) {
            return false
        }
        if (binding.iSex.tvContent.text.trim().isEmpty()) {
            return false
        }
        if (binding.etEmail.text.toString().trim().isEmpty()) {
            return false
        }
        if (binding.iArea.tvContent.text.trim().isEmpty()) {
            return false
        }
        if (binding.etCompleteAddress.text.toString().trim().isEmpty()) {
            return false
        }
        if (binding.etCode.text.toString().trim().isEmpty()) {
            return false
        }
        return true
    }



}